package cn.wxxyhw.controller;

import cn.wxxyhw.Dao.UserDao;
import cn.wxxyhw.Entity.Article;
import cn.wxxyhw.Entity.Comment;
import cn.wxxyhw.Entity.Message;
import cn.wxxyhw.Entity.User;
import cn.wxxyhw.Util.CodeUtil;
import cn.wxxyhw.Util.UnReadMessage;
import cn.wxxyhw.server.*;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * control
 * @Author: 洪稳
 * @Date: 2019/6/2
 */

@Controller
public class DispatcherServletHandler {

    @Autowired
    private MessageServer messageServer;
    @Autowired
    private UserServer userServer;
    @Autowired
    private ArticleServer articleServer;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CommentServer commentServer;
    @Autowired
    private Liuyan liuyan;
    @Autowired
    private Login login;

    /**
     * 用户登陆
     * @param username
     * @param password
     * @param
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public String login(HttpSession session,
                        @RequestParam("username") String username,
                        @RequestParam("password") String password){
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()){
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,password);
            try {
                usernamePasswordToken.setRememberMe(true);
                subject.login(usernamePasswordToken);
            }catch (Exception e){
                return "error";
            }
        }
        User login = this.login.login(username, password);
        session.setAttribute("user",login);
        return "success";
    }

    /**
     * 用户跳转页面
     * @param map
     * @return
     */
    @RequestMapping(value = "/main",method = RequestMethod.GET)
    public String main(Map<String ,User> map,HttpSession session){
        User user =(User)session.getAttribute("user");
        user = userServer.getUserByid(user.getId());
        map.put("user",user);
        return "static/main";
    }

    /**
     * 注册发送验证码
     * @param username
     * @param email
     * @return
     */
    @ResponseBody
    @RequestMapping("/regeist/sendEmail")
    public String sendEmail(@RequestParam("username") String username,
                            @RequestParam("email") String email){
        String code = CodeUtil.getCode();
        Regeist.sendEmail(username,email,code);
        return code;
    }

    /**
     * 判断用户是否存在
     * @param id 用户登陆时的id
     * @return exit 存在
     */
    @ResponseBody
    @RequestMapping("/regeist/isExit")
    public String userIsExit(@RequestParam("school") String id){
        String exit = Regeist.isExit(id);
        return exit;
    }

    /**
     * 注册用户
     * @param username 用户名
     * @param schoolid 用户id
     * @param email   用户邮箱
     * @param password  用户密码
     * @return
     */
    @ResponseBody
    @RequestMapping("/regeist")
    public String regeistUser(@RequestParam("username") String username,
                              @RequestParam("schoolid") String schoolid,
                              @RequestParam("email") String email,
                              @RequestParam("password") String password){
        User regeistUser = new User();
        regeistUser.setPassword(password);
        regeistUser.setEmail(email);
        regeistUser.setUid(schoolid);
        regeistUser.setUsername(username);
        regeistUser.setImage("/image/1561191271249");
        boolean success = Regeist.regeistUser(regeistUser);
        if (success){
            return "success";
        }
        return "error";
    }

    /**
     * 找回密码
     * @param id 用户id
     * @param email 用户注册时使用的邮箱
     * @return
     */
    @ResponseBody
    @GetMapping("/forget/{id}/{email}")
    public String forgetYZ(@PathVariable("id") String id,
                           @PathVariable("email") String email){
        System.out.println("laile");
        boolean sure = userDao.sureMsg(id,email);
        if (sure)
            return "true";

        return "false";
    }

    /**
     * 留言板
     * @param fromId
     * @param toId
     * @return
     */
    @RequestMapping("/liuyan/all")
    public String liuyan(@RequestParam("fromName") String fromId,
                         @RequestParam("toName") String toId,
                         Map<String,Object> map,
                         HttpServletRequest request){
        List<cn.wxxyhw.Entity.Liuyan> list = null;
        list = liuyan.getList(toId);
        List<Comment> allPL = commentServer.getAllPL();
        map.put("pl",allPL);
        map.put("liuyan",list);
        map.put("fromName",fromId);
        map.put("toName",toId);
        return "static/liuyanban";
    }

    /**
     * 用户留言操作
     * @param desc 留言文字
     * @param file 含有图片的文件
     * @return
     */
    @RequestMapping("/liuyan/liuyan")
    public String liuyantouser(@RequestParam("desc") String desc,
                               @RequestParam("fromName") String fromName,
                               @RequestParam("toName") String toName,
                               @RequestParam("file") MultipartFile file,
                               Map<String,Object> map){
        if(null != file.getOriginalFilename() && !"".equals(file.getOriginalFilename())){
            String time = new Date().getTime()+"";
            String realPath = "H:/upload/"+ time+".jpg";
            try {
                file.transferTo(new File(realPath));
                Thumbnails.of(realPath).scale(1f).outputQuality(0.25f).toFile(realPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            liuyan.saveLiuYan(desc,getUsername(fromName),getUsername(toName),time,fromName,toName);
        }else {
            liuyan.saveLiuYan(desc,getUsername(fromName),getUsername(toName),null,fromName,toName);
        }
        return "redirect:/liuyan/all?fromName="+fromName+"&toName="+toName;
    }

    /**
     * 前端获取图片
     * @param url
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("/image/{url}")
    public String getImage(@PathVariable("url") String url,
                            HttpServletResponse response){
        FileInputStream fis = null;
        OutputStream os = null;
        try {
                fis = new FileInputStream("H:/upload/" + url + ".jpg");

            os = response.getOutputStream();
            int count = 0;
            byte[] buffer = new byte[1024 * 8];
            while ((count = fis.read(buffer)) != -1) {
                os.write(buffer, 0, count);
                os.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            fis.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "ok";
    }

    /**
     * 留言评论保存
     * @param id
     * @param fromName
     * @param toName
     * @param desc
     * @return
     */
    @RequestMapping("/liuyan/pinglun")
    private String liuyanPingLun(@RequestParam("lyId") String id,
                                 @RequestParam("fromName") String fromName,
                                 @RequestParam("toName") String toName,
                                 @RequestParam("desc") String desc,
                                 @RequestParam("rtname") String rtname,
                                 Map<String,Object> map){
        commentServer.savePL(id,getUsername(fromName),toName==""?"":getUsername(toName),desc,fromName,toName);
        return "redirect:/liuyan/all?fromName="+fromName+"&toName="+rtname;
    }

    /**
     * 删除留言
     * @param id 留言id
     * @return
     */
    @RequestMapping("/del/ly/{id}/{toName}/{fromName}")
    private String delLy(@PathVariable("id") String id,
                         @PathVariable("toName") String toName,
                         @PathVariable("fromName") String fromName,
                         Map<String,Object> map){
        liuyan.del(id);
        commentServer.delByLyId(id,0);
        List<cn.wxxyhw.Entity.Liuyan> list = null;
        list = liuyan.getList(toName);
        List<Comment> allPL = commentServer.getAllPL();
        map.put("pl",allPL);
        map.put("liuyan",list);
        map.put("fromName",fromName);
        map.put("toName",toName);
        return "static/liuyanban";
    }

    /**
     * 删除评论
     * @param id 评论id
     * @return
     */
    @RequestMapping("/del/pl/{id}/{toName}/{fromName}")
    private String delPl(@PathVariable("id") String id,
                         @PathVariable("toName") String toName,
                         @PathVariable("fromName") String fromName,
                         Map<String,Object> map){
        commentServer.del(id);
        List<cn.wxxyhw.Entity.Liuyan> list;
        list = liuyan.getList(toName);
        List<Comment> allPL = commentServer.getAllPL();
        map.put("pl",allPL);
        map.put("liuyan",list);
        map.put("fromName",fromName);
        map.put("toName",toName);
        return "static/liuyanban";
    }

    /**
     * 全部说说（进入说说页面）
     * @param name
     * @param map
     * @return
     */
    @RequestMapping("/shuoshuo/all/{name}")
    private String shuoshuoAll(@PathVariable("name") String name,
                               Map<String,Object> map){
        List<Article> all = articleServer.getAll();
        List<cn.wxxyhw.Entity.Liuyan> list = liuyan.getList(name);
        articleServer.lookAddOne();
        List<Comment> allPL = commentServer.getAllPL();
        map.put("liuyan",list);
        map.put("shuoshuo",all);
        map.put("pl",allPL);
        map.put("name",getUsername(name));
        map.put("id",name);
        map.put("image",userDao.getImageByName(name));
        return "static/personalpage";
    }

    /**
     * 保存说说
     * @param desc 内容
     * @param file 图片
     * @param name 姓名
     * @param map
     * @return
     */
    @RequestMapping("/shuoshuo/shuoshuo")
    private String savaShuoShuo(@RequestParam("desc") String desc,
                                @RequestParam("file") MultipartFile file,
                                @RequestParam("name") String name,
                                Map<String,Object> map){
        if(null != file.getOriginalFilename() && !"".equals(file.getOriginalFilename())){
            String time = new Date().getTime()+"";
            String realPath = "H:/upload/"+ time+".jpg";
            try {
                file.transferTo(new File(realPath));
                Thumbnails.of(realPath).scale(1f).outputQuality(0.25f).toFile(realPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            articleServer.saveLiuYan(desc,name,time,name);
        }else {
            articleServer.saveLiuYan(desc,name,null,name);
        }
        return "redirect:/shuoshuo/all/"+name;
    }

    /**
     * 点赞
     * @param id
     * @param option
     */
    @ResponseBody
    @RequestMapping("/shuoshuo/dz/{id}/{option}")
    private void shuoshuodz(@PathVariable("id") String id,@PathVariable("option") String option){
        articleServer.dz(id,option);
    }

    /**
     * 删除说说
     * @param id 说说id
     * @param
     * @return
     */
    @RequestMapping("/del/shuoshuo/{id}/{name}")
    private String shuoshuodel(@PathVariable("id") int id,
                               @PathVariable("name") String name){
        articleServer.del(id);
        commentServer.delByLyId(0+"",id);
        return "redirect:/shuoshuo/all/"+name;
    }

    /**
     * 说说保存评论
     * @param articleId
     * @param desc
     * @param name
     * @param
     * @return
     */
    @RequestMapping("/shuoshuo/pl")
    private String shuoshuopl(@RequestParam("articleId") int articleId,
                              @RequestParam("desc") String desc,
                              @RequestParam("name") String name,
                              @RequestParam("toName") String toName){
        commentServer.savePL(articleId,desc,getUsername(name),toName==""?"":getUsername(toName),null,name,toName);
        return "redirect:/shuoshuo/all/"+name;
    }

    /**
     * 删除说说评论
     * @param id
     * @param name
     * @param map
     * @return
     */
    @RequestMapping("/del/pl/{id}/{name}")
    private String shuoshuodelpl(@PathVariable("id") String id,
                                 @PathVariable("name") String name,
                                 Map<String,Object> map){
        commentServer.del(id);
        return "redirect:/shuoshuo/all/"+name;
    }

    /**
     * 好友列表
     * @param name
     * @return
     */
    @RequestMapping("/all/friends/{name}")
    private String friends(@PathVariable("name") String name,
                           Map<String,Object> map){
        List<UnReadMessage> messages = messageServer.getNoReadMessage(name);
        List<User> list = userServer.getAll(name);
        map.put("users",list);
        map.put("name",name);//自己的用户名
        map.put("message",messages);
        return "/static/caller";
    }

    /**
     * 查询修改信息的id
     * @param id
     * @param map
     * @return
     */
    @RequestMapping("/info/{id}")
    private String info(@PathVariable("id") int id,
                        Map<String,Object> map){
        User user = userServer.getUserByid(id);
        map.put("user",user);
        map.put("username",user.getUid());
        return "/static/info";
    }

    /**
     * 更新信息
     * @param id
     * @param uid
     * @param nickname
     * @param email
     * @param file
     * @param map
     * @return
     */
    @RequestMapping("/info/update")
    private String updateInfo(@RequestParam("id") int id,
                              @RequestParam("username") String uid,
                              @RequestParam("nickname")String nickname,
                              @RequestParam("email") String email,
                              @RequestParam("file") MultipartFile file,
                              Map<String,Object> map){
        if(file.getSize()==0 || null != file.getOriginalFilename() || !"".equals(file.getOriginalFilename())) {
            String time = new Date().getTime() + "";
            String realPath = "H:/upload/" + time + ".jpg";
            try {
                file.transferTo(new File(realPath));
                Thumbnails.of(realPath).scale(1f).outputQuality(0.15f).toFile(realPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            userServer.update(uid,nickname,email,time);
        }else {
            userServer.update(uid,nickname,email,null);
        }
        User user = userServer.getUserByid(id);
        map.put("user",user);
        map.put("username",user.getUid());
        return "/static/info";
    }

    /**
     * 跳转修改密码页面
     * @param id
     * @param map
     * @return jsp
     */
    @RequestMapping("/password/{id}")
    private String password(@PathVariable("id") int id,
                            Map<String,Object> map){
        map.put("id",id);
        return "/static/password";
    }

    /**
     * 修改密码
     * @param pw  新密码
     * @param opw 旧密码
     * @param id 用户主键id
     * @return error  /rePassword/'+id+'/'+pw+'/'+oldpassw
     */
    @ResponseBody
    @RequestMapping("/rePassword/{id}/{pw}/{opw}")
    private String rePassword(@PathVariable("id") int id,
                              @PathVariable("pw") String pw,
                              @PathVariable("opw") String opw){
        String restut = userServer.updatePassword(pw,opw,id);
        return restut;
    }

    /**
     * 聊天跳转
     * @param friendId 对方Id
     * @param map
     * @param session
     * @return
     */
    @RequestMapping("/chat/{friendId}")
    private String chat(@PathVariable("friendId") String friendId,
                        Map<String,Object> map,
                        HttpSession session){
        User friend = userServer.getImageById(friendId);
        User user =(User)session.getAttribute("user");
        List<Message> messages = messageServer.getNoReadMessageDetail(friendId,user.getUid());
        map.put("message",messages);
        map.put("myId",user.getUid());
        map.put("otherId",friendId);
        map.put("friendUsername",friend.getUsername());
        map.put("friendImage",friend.getImage().split("\\/")[2]);
        String image = user.getImage().split("\\/")[2];
        map.put("image",image);
        return "/static/chat";
    }

    /**
     * 聊天时发送图片
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/chat/upload/image",produces = "application/json;charset=utf-8")
    private String chatImage(MultipartFile file){
        String time = new Date().getTime()+"";
        String realPath = "H:/upload/"+ time+".jpg";
        try {
            file.transferTo(new File(realPath));
            Thumbnails.of(realPath).scale(1f).outputQuality(0.15f).toFile(realPath);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "{" +"\"code\":"+0+",\"msg\":\"\","+"\"data\":{\"src\":\""+"/image/"+time+"\"}}";
    }

    /**
     * 聊天是上传文件
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/chat/upload/file" ,produces = "application/json;charset=utf-8")
    private String chatFile(MultipartFile file, HttpServletRequest request,HttpServletResponse response){
        String filename = file.getOriginalFilename();
        String fileType = file.getOriginalFilename().split("\\.")[1];
        String time = new Date().getTime()+".";
        String realPath = "H:/upload/"+ time+fileType;
        try {
            file.transferTo(new File(realPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "{" +"\"code\":"+0+",\"msg\":\"\","+"\"data\":{\"src\":\""+"/file/download/"+time+"/"+fileType+"\",\"name\":\""+filename+"\"}}";
    }

    /**
     * 文件下载
     * @param name 文件名
     * @param type 文件类型
     * @return
     * @throws Exception
     */
    @RequestMapping("/file/download/{name}/{type}")
    public ResponseEntity<byte[]> filexiazai(@PathVariable("name") String name, @PathVariable("type") String type) throws Exception{
        byte[] body = null;
        FileInputStream fileInputStream = new FileInputStream("H:/upload/"+name+type);
        body= new byte[fileInputStream.available()];
        fileInputStream.read(body);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition","attachment;filename="+name+type);
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(body,headers, HttpStatus.CREATED);
        return responseEntity;
    }

    /**
     * 查询聊天记录
     * @param uid 用户id
     * @param session
     * @param map
     * @return
     */
    @RequestMapping("/chatRecord/{uid}")
    public String chatRecord(@PathVariable("uid") String uid,HttpSession session,Map<String ,Object> map){
        User user = (User) session.getAttribute("user");
        User friend = userServer.getImageById(uid);
        List<Message> messages = messageServer.getMessage(uid,user.getUid());
        map.put("message",messages);
        map.put("friend",friend);
        map.put("my",user);
        return "/static/chatRecord";
    }

    /**
     * 跳转获取房间号
     * @return
     */
    @RequestMapping("/allChat")
    public String chat(){
        return "/static/yanzheng";
    }

    /**
     * 跳转至具体群聊
     * @param id
     * @return
     */
    @RequestMapping("/qunChat")
    public String qunChat(@RequestParam("id") int id,
                          HttpSession session,
                          Map<String,Object> map){
        User user = (User)session.getAttribute("user");
        String image = user.getImage().split("\\/")[2];
        map.put("user",user);
        map.put("id",id);
        map.put("image",image);
        return "/static/qunchat";
    }

    /**
     * 根据id查询用户名
     * @param id 用户id
     * @return 用户昵称
     */
    public String getUsername(String id){
        String username = userDao.getUserNameById(id);
        return username;
    }

    @ResponseBody
    @RequestMapping("/image/{url}/{type}")
    public String getImage(@PathVariable("url") String url,
                           @PathVariable("type") String type,
                           HttpServletResponse response){
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            fis = new FileInputStream("E:/images/" + url + "."+type);

            os = response.getOutputStream();
            int count = 0;
            byte[] buffer = new byte[1024 * 8];
            while ((count = fis.read(buffer)) != -1) {
                os.write(buffer, 0, count);
                os.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            fis.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "ok";
    }

}





















